<?php
namespace App\Models\ProjectAuth;

use App\Facades\ScarecrowAuth;
use Illuminate\Support\Facades\DB;

class ProjectManageModel{
    /**
     * 创建项目
     * @param $allData
     * @return array
     */
    public function createProject($allData) {
        $projectName = $allData['projectName'];
        $projectObj = DB::table('sc_api_doc_project')->whereRaw("state!=9 AND name=?", [$projectName])->first();
        if ($projectObj) {
            return ModelReturn(1, '创建失败,项目名已存在');
        }

        $insertData = [
            'name'  =>  $projectName,
            'state' =>  1
        ];
        $iCnt = DB::table('sc_api_doc_project')->insertGetId($insertData);
        if ($iCnt) {
        	$allData['id'] = $iCnt;
        	HandleLog()->addLog('i', $allData, '创建了项目');
            return ModelReturn(0, '创建成功');
        } else {
            return ModelReturn(2,'创建失败');
        }
    }

    /**
     * 编辑项目
     * @param $allData
     * @return array
     */
    public function editProject($allData) {
        $projectName = $allData['projectName'];
        $projectId = $allData['projectId'];

        $projectObj = DB::table('sc_api_doc_project')->whereRaw("state!=9 AND id=?", [$projectId])->first();
        if (!$projectObj) {
            return ModelReturn(1, '项目不存在,编辑失败');
        }
		$projectObj = (array)$projectObj;

        if ($projectObj['name'] == $projectName) {
            return ModelReturn(0, '编辑成功');
        }

        $obj = DB::table('sc_api_doc_project')->whereRaw("id!=? AND state!=9 AND name=?", [$projectId, $projectName])->first();
        if ($obj) {
            return ModelReturn(1, '项目名称已存在');
        }

        $iCnt = DB::table('sc_api_doc_project')->where('id', $projectId)->update([
            'name'  =>  $projectName
        ]);
        if ($iCnt) {
			HandleLog()->addLog('u', $allData, '编辑了项目');
            return ModelReturn(0, '编辑成功');
        } else {
            return ModelReturn(2, '编辑失败');
        }
    }

    /**
     * 改变项目状态
     * @param $allData
     * @return array
     */
    public function changeProjectState($allData) {
        $projectId = $allData['projectId'];

        $projectObj = DB::table('sc_api_doc_project')->whereRaw("state!=9 AND id=?", [$projectId])->first();
        if (!$projectObj) {
            return ModelReturn(1, '项目不存在,改变状态失败');
        }


        $iCnt = DB::table('sc_api_doc_project')->where('id', $projectId)->update([
            'state'  =>  $projectObj->state == 1 ? 2 : 1
        ]);
        if ($iCnt) {
			HandleLog()->addLog('u', $allData, '改变了项目状态');
            return ModelReturn(0, '修改成功');
        } else {
            return ModelReturn(2, '修改失败');
        }
    }

    /**
     * 删除项目
     * @param $allData
     * @return array
     */
    public function deleteProject($allData) {
        $projectId = $allData['projectId'];

        $projectObj = DB::table('sc_api_doc_project')->whereRaw("state!=9 AND id=?", [$projectId])->first();
        if (!$projectObj) {
            return ModelReturn(1, '项目不存在,删除失败');
        }


        $iCnt = DB::table('sc_api_doc_project')->where('id', $projectId)->update([
            'state'  =>  9
        ]);
        if ($iCnt) {
			HandleLog()->addLog('d', $allData, '删除了项目');
            return ModelReturn(0, '删除成功');
        } else {
            return ModelReturn(2, '删除失败');
        }
    }

    /**
     * 创建分类
     * @param $allData
     * @return array
     */
    public function createCategory($allData) {
        $categoryName = $allData['categoryName'];
        $projectId = $allData['projectId'];

        if (!ScarecrowAuth::hasAuthEditProject($projectId, APP_USER_TOKEN)) {
            return ModelReturn(1, '无权限进行操作');
        }

        $projectObj =DB::table('sc_api_doc_project')->whereRaw("state!=9 AND id={$projectId}")->first();
        if (!$projectObj) {
        	return ModelReturn(3, '项目不存在,创建失败');
		}

        $categoryObj = DB::table('sc_api_doc_category')->whereRaw("state=1 AND name=? AND project_id=?", [$categoryName, $projectId])->first();
        if ($categoryObj) {
            return ModelReturn(1, '创建失败,项目下该分类名已存在');
        }

        $insertData = [
            'name'  =>  $categoryName,
            'project_id'  =>  $projectId,
            'state' =>  1
        ];
        $iCnt = DB::table('sc_api_doc_category')->insertGetId($insertData);
        if ($iCnt) {
			$allData['id'] = $iCnt;
			HandleLog()->addLog('i', $allData, '创建了分类');
            return ModelReturn(0, '创建成功');
        } else {
            return ModelReturn(2,'创建失败');
        }
    }

    /**
     * 编辑分类
     * @param $allData
     * @return array
     */
    public function updateCategory($allData) {
        $categoryName = $allData['categoryName'];
        $categoryId = $allData['categoryId'];

        $categoryObj = DB::table('sc_api_doc_category')->whereRaw("state=1 AND id=?", [$categoryId])->first();
        if (!$categoryObj) {
            return ModelReturn(1, '分类不存在,编辑失败');
        }

		$categoryObj = DbObjectToArr($categoryObj);
        if (!ScarecrowAuth::hasAuthEditProject($categoryObj['project_id'], APP_USER_TOKEN)) {
            return ModelReturn(1, '无权限进行操作');
        }

        if ($categoryObj['name'] == $categoryName) {
            return ModelReturn(0, '编辑成功');
        }
        $projectId = $categoryObj['project_id'];
        $obj = DB::table('sc_api_doc_category')->whereRaw("id!=? AND project_id=? AND state=1 AND name=?", [$categoryId, $projectId, $categoryName])->first();
        if ($obj) {
            return ModelReturn(1, '项目下该分类名称已存在');
        }

        $iCnt = DB::table('sc_api_doc_category')->where('id', $categoryId)->update([
            'name'  =>  $categoryName
        ]);
        if ($iCnt) {
			HandleLog()->addLog('u', $allData, '编辑了分类');
            return ModelReturn(0, '编辑成功');
        } else {
            return ModelReturn(2, '编辑失败');
        }
    }

    /**
     * 删除分类
     * @param $allData
     * @return array
     */
    public function deleteCategory($allData) {
        $categoryId = $allData['categoryId'];

        $categoryObj = DB::table('sc_api_doc_category')->whereRaw("state=1 AND id=?", [$categoryId])->first();
        if (!$categoryObj) {
            return ModelReturn(1, '分类不存在,删除失败');
        }

		$categoryObj = DbObjectToArr($categoryObj);
        if (!ScarecrowAuth::hasAuthEditProject($categoryObj['project_id'], APP_USER_TOKEN)) {
            return ModelReturn(1, '无权限进行操作');
        }

        $iCnt = DB::table('sc_api_doc_category')->where('id', $categoryId)->update([
            'state'  =>  9
        ]);
        if ($iCnt) {
			HandleLog()->addLog('d', $allData, '删除了分类');
            return ModelReturn(0, '删除成功');
        } else {
            return ModelReturn(2, '删除失败');
        }
    }

	/**
	 * 获取所有可以编辑项目
	 * @param string $projectName
	 * @return array
	 */
    public function getAllCanEditProject($projectName = '') {
    	if (ScarecrowAuth::isAdmin(APP_USER_TOKEN)) {
			$projectListObj = DB::table('sc_api_doc_project as t1')->whereRaw("t1.state!=9");
		} else {
    		$userId = ScarecrowAuth::id(APP_USER_TOKEN);
			$isAllProjectAuth = DB::table('sc_user_all_project_auth')->where(['user_id'=>$userId])->first();
			if ($isAllProjectAuth) {
				$projectListObj = DB::table('sc_api_doc_project as t1')->whereRaw("t1.state!=9");
			} else {
				$projectListObj = DB::table('sc_user_project_auth as t1')->leftJoin('sc_api_doc_project as t2', 't1.project_id','=','t2.id')->whereRaw("t1.user_id=? AND t2.state=1", [$userId])->select('t2.*');
			}
        }

    	if ($projectName) {
			$projectListObj->whereRaw("t1.name like '%{$projectName}%'");
		}

		$projectList = $projectListObj->get();
    	$allCanEditProjectList = DbObjectToArr($projectList);

    	if ($allCanEditProjectList) {
			$allProjectId = array_column($allCanEditProjectList, 'id');
			$categoryNumListObj = DB::table('sc_api_doc_category')->whereIn('project_id', $allProjectId)->groupBy('project_id')->select(["project_id",DB::raw("COUNT(id) as categoryNum")])->get();
			$apiNumListObj = DB::table('sc_api_doc')->whereIn('project_id', $allProjectId)->groupBy('project_id')->select(["project_id",DB::raw("COUNT(id) as categoryNum")])->get();
			$categoryNumList = [];
			foreach ($categoryNumListObj as $item) {
				$categoryNumList[$item->project_id] = $item->categoryNum;
			}

			$apiNumList = [];
			foreach ($apiNumListObj as $item) {
				$apiNumList[$item->project_id] = $item->categoryNum;
			}
    	}

    	foreach ($allCanEditProjectList as &$item) {
			$item['categoryNum'] = 0;
			$item['apiNum'] = 0;

			if (array_key_exists($item['id'], $categoryNumList)) {
				$item['categoryNum'] = $categoryNumList[$item['id']];
			}

			if (array_key_exists($item['id'], $apiNumList)) {
				$item['apiNum'] = $apiNumList[$item['id']];
			}
		}

		return ModelReturn(0, "获取成功", $allCanEditProjectList);
	}

    /**
     * 获取所有可以查看的项目列表
     * @return array
     */
	public function getAllCanViewProject() {
        if (ScarecrowAuth::isAdmin(APP_USER_TOKEN)) {
            $projectList = DB::table('sc_api_doc_project')->whereRaw("state!=9")->get();
            return ModelReturn(0, '获取成功', DbObjectToArr($projectList));
        }

		$userId = ScarecrowAuth::id(APP_USER_TOKEN);
        $isAllProjectAuth = DB::table('sc_user_all_project_auth')->where(['user_id'=>$userId])->first();
        if ($isAllProjectAuth) {
			$projectList = DB::table('sc_api_doc_project')->whereRaw("state!=9")->get();
			return ModelReturn(0, '获取成功', DbObjectToArr($projectList));
		}

        $projectList = DB::table('sc_user_project_auth as t1')->leftJoin('sc_api_doc_project as t2', 't1.project_id','=','t2.id')->whereRaw("t1.user_id=? AND t2.state=1", [$userId])->select('t2.*')->get();
        $projectList = DbObjectToArr($projectList);
        $userId = ScarecrowAuth::id(APP_USER_TOKEN);
        $allCanReadApiList = DB::table('sc_user_read_api_doc')->where('user_id', $userId)->pluck('api_doc_id')->toArray();
        if ($allCanReadApiList) {
            $allCanReadApiProjectId = DB::table('sc_api_doc')->whereIn('id', $allCanReadApiList)->groupBy('project_id')->pluck('project_id')->toArray();
            if ($allCanReadApiProjectId) {
                $projectAddList = DB::table('sc_api_doc_project')->whereIn('id', $allCanReadApiProjectId)->whereRaw("state=1")->get();
                $projectList = array_merge($projectList, DbObjectToArr($projectAddList));
            }
        }

        return ModelReturn(0, '获取成功', DbObjectToArr($projectList));
    }

    /**
     * 获取所有分类
     * @param $projectId
     * @return array
     */
	public function getAllCategory($projectId, $categoryName='') {
		$userId = ScarecrowAuth::id(APP_USER_TOKEN);
		$isProjectManage = DB::table('sc_user_project_auth')->where(['user_id'=>$userId, 'project_id'=>$projectId])->first();
		$isAllProjectManage = DB::table('sc_user_all_project_auth')->where(['user_id'=>$userId])->first();
	    if (ScarecrowAuth::hasAuthEditProject($projectId, APP_USER_TOKEN) || $isProjectManage || $isAllProjectManage) {
            $categoryListObj = DB::table('sc_api_doc_category')->whereRaw("state=1 AND project_id=?", [$projectId]);
            if ($categoryName) {
				$categoryListObj->whereRaw("name like '%{$categoryName}%'");
			}
			$categoryList = $categoryListObj->get();
        } else {
            $allApiDocList = DB::table('sc_user_read_api_doc')->where(['user_id'=>$userId])->pluck('api_doc_id')->toArray();
			$allCategoryIdList=  [];
			if ($allApiDocList) {
				$allCategoryIdList = DB::table('sc_api_doc')->where(['project_id'=>$projectId])->whereIn('id', $allApiDocList)->pluck('category_id')->toArray();
			}

			$allCategoryIdList = array_unique($allCategoryIdList);
			$categoryList = [];
            if ($allCategoryIdList) {
				$categoryListObj = DB::table('sc_api_doc_category')->whereIn('id', $allCategoryIdList);
				if ($categoryName) {
					$categoryListObj->whereRaw("name like '{$categoryName}'");
				}
				$categoryList = $categoryListObj->get();
            }
        }
		$categoryList = DbObjectToArr($categoryList);
	    $allCategoryIdList = array_column($categoryList, 'id');
		$allApiNumListObj = DB::table('sc_api_doc')->whereIn('category_id', $allCategoryIdList)->groupBy('category_id')->select(["category_id", DB::raw("COUNT(id) as apiNum")])->get();
		$allApiNumListObj = DbObjectToArr($allApiNumListObj);
		$allApiNumList = [];
		foreach ($allApiNumListObj as $item) {
			$allApiNumList[$item['category_id']] = $item['apiNum'];
		}

		foreach ($categoryList as &$item) {
			$item['apiNum'] = $allApiNumList[$item['id']] ?? 0;
		}
		return ModelReturn(0, "获取成功", $categoryList);
	}

	/**
	 * 获取项目信息
	 * @param $projectId
	 * @return array
	 */
	public function getProjectInfo($projectId) {
		$projectObj = DB::table('sc_api_doc_project')->whereRaw("state!=9 AND id=?", [$projectId])->first();
		if (!$projectObj) {
			return ModelReturn(1, '项目不存在');
		}
		return ModelReturn(0, '获取成功', (array)$projectObj);
	}

	/**
	 * 获取分类信息
	 * @param $projectId
	 * @param $categoryId
	 * @return array
	 */
	public function getCategoryInfo($projectId, $categoryId) {
		$categoryObj = DB::table('sc_api_doc_category')->where(['id'=>$categoryId, 'project_id'=>$projectId])->first();
		if (!$categoryObj) {
			ModelReturn(1, '分类不存在');
		}
		$categoryObj = DbObjectToArr($categoryObj);
		return ModelReturn(0, '获取成功', $categoryObj);
	}
}